<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use fast\Random;
use phpCAS;
use think\Session;
use think\helper\Time;
use app\admin\model\Outsideschool as outside;
use think\Config;
use think\Db;
use app\admin\model\ReceptionUnit;
use think\Validate;
use app\admin\logic\ZHXY;
use think\Cache;


class Outsideschool extends Frontend
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $layout = 'weiui';
    protected $model = null;


    public function _initialize(){

        parent::_initialize();
        if (!Session::get('uid')){
//            require_once ROOT_PATH.'\public\cas\index1.php';
        }
        $this->model = new outside();
        $action = strtolower(request()->action());

        //调试使用
        if (input('admin') == 'super'){
            $_SESSION['uid'] = '200501067';
            $_SESSION['cn'] = '马伟萍';
        }
        //调试使用
        if (input('admin') == 'yuning'){
            $_SESSION['uid'] = '200201092';
            $_SESSION['cn'] = '于宁';
        }

        if(!empty($_GET['type'])&&$_GET['type']==1)
        {
            $_SESSION['uid'] = '198601025';
            $_SESSION['cn'] = '张文军';
        }
       // $_SESSION['uid'] = '199401025';
       // $_SESSION['cn'] = '肖传强';

        if (in_array($action, ['index','view', 'ajax','log', 'info'])){
            // if(empty($_COOKIE['keeplogin'])){
                if (!isset($_SESSION['uid']) || $_SESSION['uid'] == ""){
                    $this->redirect(request()->domain() . '/cas/index.php');
                    exit;
                }
                session('uid', $_SESSION['uid']);
                session('cn', $_SESSION['cn']);
            // }
            // $_COOKIE['keeplogin'] = 86400 * 7 +time();
        }
    
        
    }

    public function index($ids = 1){
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");

            if(strlen($params['card_id'])==18){
               $idc=$this->is_idcard($params['card_id']);
                if(!$idc){
                    $this->error('身份证错误');
                }
            }
            //黑名单
            $re = $this->blacklist($params['nickname']);
            if (!$re){
                $this->error('你好，此用户不允许入校');
            }
	        if($params['tel']=='13789856889' || $params['tel']=='15666666774' || $params['tel']=='15763913187'){
                $this->error('你好，此用户不允许入校');
            }
            $params['create_time'] = time();
            if(!empty(session('uid')) && session('uid')=='15610001073'){
                $params['applier_id'] = '202302175';
                $params['applier_name'] = '林 雪 菲';
            }else{
                $params['applier_id'] = session('uid')?:'';//申请人id
                if(empty($params['applier_name'])){
                    $check_cn = Db::name('teacher')->where(['tel' => session('uid'),'type'=>1])->value('nickname');
                    if(!empty(session('cn'))){
                        $applier_name = session('cn');
                    }else{
                        if(!empty($check_cn)){
                            $applier_name = $check_cn;
                        }else{
                            $applier_name = '';
                        }
                    }
                    $params['applier_name'] = $applier_name;//申请人名称
                }
            }
            $info = ReceptionUnit::get($params['reception_id']);
            $params['reception_name'] = $info['name'];
            if ($params['admission_starttime'])
                $params['admission_starttime'] = str_replace('/', '', $params['admission_starttime']);
            if ($params['admission_endtime'])
                $params['admission_endtime'] = str_replace('/', '', $params['admission_endtime']);
            if ($params['admission_endtime'] < $params['admission_starttime'])
                $this->error('入校截止时间不能小于入校开始时间');

            $last_month = strtotime('+30 day',strtotime($params['admission_starttime']));
            if(strtotime($params['admission_endtime'])>$last_month){
                $this->error('入校开始和截止时间间隔不可大于30天');
            }
            $res = $this->model->allowField(true)->save($params);
            if ($res){
                if($info -> sid){
                    $sid_arr = explode(',',$info->sid);
                    foreach($sid_arr as $key => $v){
                        if($params['nickname']!='马建华'){
                            send_wechat_work_msg([$v], '<a href="https://yqsb.qau.edu.cn/index/outsideschool/view">您有一份校外人员'.$params['applier_name'].'提交的入校预约申请需要审批。</a>');
                        }
                    }
                    
                    if($params['nickname']!='贾小兵'){
                        $name_arr = explode(',',$info['nickname']);
                        foreach ($name_arr as $ke => $val) {
                           $name_arr2[] = $val."审批";
                        }
                        $inst_id = uniqid('outside').mt_rand(100000, 999999);
                        $app_id = uniqid('outside').mt_rand(100000, 999999);
                        $appname = '校外人员入校';
                        $task_id = uniqid('outside').mt_rand(100000, 999999);
                        $created_key = 'zhxy_create_' . (string)$app_id;
                        $created     = Cache::get($created_key);
                        if (!$created) {
                            // 没有创建app
                            $re = $this->push_apps($app_id,$appname);
                            if ($re[0]) {
                                Cache::set($created_key, 1, 3600 * 48);
                            }
                        }
                        
                        $href_url = 'https://yqsb.qau.edu.cn/index/outsideschool/view';
                        $arr['inst_data'] = [[
                            "inst_id"=>$inst_id,
                            "app_id"=>$app_id,
                            "creator"=>$params['applier_id'],
                            "created"=>date('Y-m-d H:i:s'),
                            "finished"=>"",
                            "percent"=>0,
                            "status"=>0,
                            'node_id'=>[$this->model->id],
                            "node_name"=>$name_arr2,
                            // "node_name"=>["郝老师审批"],
                            "name"=>"校外人员(".$params['nickname'].")进校申请",
                            "form_url_view"=>$href_url,
                            "form_mobile_url_view"=>$href_url,
                            "thirdparty_id"=>config('zhxy.outside_thirdparty_id'),
                            "process_pic_url"=>"",
                            "conversion_column"=>['app_id','inst_id','node_id','task_id']
                        ]];
                        $arr['task_data'] = [[
                            "inst_id"=>$inst_id,
                            "app_id"=>$app_id,
                            "task_id"=>$task_id,
                            "node_id"=>$this->model->id,
                            "status"=>0,
                            "created"=>date('Y-m-d H:i:s'),
                            "finished"=>"",
                            "form_url"=>$href_url,
                            "form_url_view"=>$href_url,
                            "form_mobile_url"=>$href_url,
                            "form_mobile_url_view"=>$href_url,
                            "process_pic_url"=>"",
                            "thirdparty_id"=>config('zhxy.outside_thirdparty_id'),
                            "node_name"=>$info['nickname']."审批",
                            "number"=>$sid_arr,
                            "conversion_column"=>['app_id','inst_id','node_id','task_id']
                        ]];
                        $url  = config('zhxy.push-task');
                        $data =  $this->send_zhxy_msg($url,$arr,'outside');
                        if($data[0] && $data[1]=='发送成功'){
                            $outside_zhxy = [
                                'inst_id'=>$inst_id,
                                'app_id'=>$app_id,
                                'task_id'=>$task_id,
                            ];
                            Db::name('outsideschool')->where('id',$this->model->id)->update(['outside_zhxy_json'=>json_encode($outside_zhxy)]);
                        }
                    }

                }
                $this->success('登记成功', '', ['nickname' => $params['nickname']]);
            }
            else{
                $this->error('登记失败');
            }
        }
        //接待单位
        $where = [];
        //测试用部门
        if (!input('admin_test')){
            $where['id'] = ['<>',1];
        }
        $reception_unit = ReceptionUnit::where($where)->where('sort>0')->order('sort')->field("name,id")->select();
        $this->assign('reception_unit', $reception_unit);

        $this->assign('ids', $ids);
        $title = '入校登记';
        $this->assign('pageTitle', $title);

        $teacherid=0;
        $teacher = Db::name('teacher')->where(['tel'=>$_SESSION['uid'],'nickname'=>$_SESSION['cn']])->find();
        if($teacher){
            $teacherid = $teacher['tel'];
        }
        $this->assign('teacherid', $teacherid);
        $this->assign('applier_name', $_SESSION['cn']);

        if(!empty(session('uid'))){
            if(strlen(session('uid'))!=9){
                $this->error('暂无权限');
            }
        }
        return $this->fetch();
    }

    public function index2($ids = 1){
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            //黑名单
            //$re = $this->blacklist($params['tel'],$params['card_id']);
            $re = $this->blacklist($params['nickname']);
            if (!$re){
                $this->error('你好，此用户不允许登录');
            }
            $params['create_time'] = time();
            $params['applier_id'] = session('uid')?:'';//申请人id

            $params['applier_name'] = session('cn')?:'';//申请人名称
            $info = ReceptionUnit::get($params['reception_id']);
            $params['reception_name'] = $info['name'];
            if ($params['admission_starttime'])
                $params['admission_starttime'] = str_replace('/', '', $params['admission_starttime']);
            if ($params['admission_endtime'])
                $params['admission_endtime'] = str_replace('/', '', $params['admission_endtime']);
            if ($params['admission_endtime'] < $params['admission_starttime'])
                $this->error('入校截止时间不能小于入校开始时间');
//            $res = $this->model->allowField(true)->save($params);
            // $msg = urlencode(mb_convert_encoding("您有一份{$params['applier_name']}老师提交的校外人员入校预约申请需要审批。",'gb2312'));
//            $url = 'http://114.255.71.158:8061/?username=qdnydx&password=QAUnmc123&message='.$msg.'&phone='.($info -> mobile).'&epid=122985&linkid=&subcode=';
            // $url = 'http://114.255.71.158:8061/?username=qdnydx&password=QAUnmc123&message='.$msg.'&phone=15954275057,18153227097&epid=122985&linkid=&subcode=';
            // geturl($url);

            // send_wechat_work_msg([15954275057], '<a href="https://yqsb.qau.edu.cn/index/outsideschool/view">您有一份校外人员'.$params['applier_name'].'提交的入校预约申请需要审批。</a>');

//            if ($res){
//                if($info -> mobile){
//                    $msg = urlencode(mb_convert_encoding("您有新的入校申请待审核，申请人{$params['applier_name']}，校外入校人{$params['nickname']}",'gb2312'));
//                    echo $url = 'http://114.255.71.158:8061/?username=qdnydx&password=QAUnmc123&message='.$msg.'&phone='.($info -> mobile).'&epid=122985&linkid=&subcode=';
//                }
//                $this->success('登记成功', '', ['nickname' => $params['nickname']]);
//            }
//            else{
//                $this->error('登记失败');
//            }
        }
        //接待单位
        $where = [];
        //测试用部门
        if (!input('admin_test')){
            $where['id'] = ['<>',1];
        }
        $reception_unit = ReceptionUnit::where($where)->where('sort>0')->order('sort')->field("name,id")->select();
        $this->assign('reception_unit', $reception_unit);

        $this->assign('ids', $ids);
        $title = '入校登记';
        $this->assign('pageTitle', $title);
        return $this->fetch('index');
    }

    /**
     * 查看列表
     */
    public function view(){

        if ($this->request->isPost()){
            $page = input('page', 1);
            $page_size = input('size', 10);
            $is_check = trim(input('is_check', ''));
            $keyword = trim(input('keyword', ''));

            $where = array();
//            $where['is_check'] = 0;

            // 判断是否登录,登录后返回session
            $sid = Session::get('uid');
            $nickname = Session::get('cn');
            // 获取当前负责人所在的接待单位id
//            $reception_info = ReceptionUnit::where(['sid' => $sid, 'nickname' => $nickname])->field("name,id")->find();
            if($sid=='200101024'){ //车广杰有多个学校审核权限
                $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sid)")->field("name,id")->column('id');
            }else{
                //其他
                $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sid)")->field("name,id")->find();
            }
            
            if (!empty($reception_info)){
                if($sid=='200101024'){
                    $where['reception_id'] = ['in',$reception_info];
                }else{
                    $where['reception_id'] = $reception_info['id'];
                }
            } else{
                // 上面是先从校外人员审批人中找，这里是从校友审批人查找
                $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sf_sid)")->field("id")->find();
                if (!empty($reception_info)){
                    $where['reception_id'] = $reception_info['id'];
                    $where['is_schoolfriend'] = 1;
                }else{
                    $where['reception_id'] = '--';
                }
            }
            if (strlen($is_check) > 0){
                $where['is_check'] = $is_check;
            }
            if ($is_check == 0){
                $where['admission_endtime'] = ['>=',date('Ymd')];
            }
            if (strlen($keyword) > 0){
                $where['tel'] = ['like', '%' . $keyword . '%'];
            }

            //社会合作处，于宁，张正明可查看审核全部的校友入校
            if($sid=='200201092'|| $sid=='199501036'){
                unset($where['reception_id']);
                $where['is_schoolfriend']=1;
            }

            $outside_list = $this->model->where($where)->where('reception_id>0')->order('id desc')->paginate($page_size)->toArray();
            foreach ($outside_list['data'] as $k => &$v){
                $v['key'] = (($page - 1) * $page_size) + 1 + $k;
            }
            return $this->success('success', '', $outside_list);
        }
        $this->assign('check_option', outside::is_check);

        $title = '';
        $this->assign('pageTitle', $title);
        $this->assign('page_type', 'view');
        $this->assign('go_list', '<div class="apply-list"><a href="log">申请记录</a>');

        $teacherid=0;
        $teacher = Db::name('teacher')->where(['tel'=>session('uid')])->find();
        if($teacher){
            $teacherid = $teacher['tel'];
        }

        $sid = Session::get('uid');
        $is_reception = 0;
        $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sid)")->field("name,id")->find();
        if (!empty($reception_info)){
            $is_reception =1;
        }else{
            $reception_info_xy = ReceptionUnit::whereRaw("find_in_set('{$sid}',sf_sid)")->field("name,id")->find();
            if(!empty($reception_info_xy)){
                $is_reception =2;
            }
        }

        $this->assign('is_reception', $is_reception);
        $this->assign('teacherid', $teacherid);


        return $this->fetch();
    }
    /**
     * 查看列表
     */
    public function log(){
        if(input('demo') && input('demono')){
            Session::set('demo',input('demo'));
            Session::set('demono',input('demono'));
        }
        if ($this->request->isPost()){
            $page = input('page', 1);
            $page_size = input('size', 10);
            $is_check = trim(input('is_check', ''));
            $keyword = trim(input('keyword', ''));

            $where = array();
//            $where['is_check'] = 0;

            // 判断是否登录,登录后返回session
            $sid = Session::get('uid');

            $where['applier_id'] = $sid;
            if(session('demo') && session('demono')){
                $where['applier_id'] = session('demono');
            }

            if (strlen($is_check) > 0){
                $where['is_check'] = $is_check;
            }
//            if ($is_check == 0){
////                $where['admission_starttime'] = ['<=',date('Ymd')];
//                $where['admission_endtime'] = ['>=',date('Ymd')];
//            }
            if (strlen($keyword) > 0){
                $where['tel'] = ['like', '%' . $keyword . '%'];
            }

            $outside_list = $this->model->where($where)->order('id desc')->paginate($page_size)->toArray();

            foreach ($outside_list['data'] as $k => &$v){
//                $v['admission_time'] = date('Y-m-d', strtotime($v['admission_time']));
                $v['key'] = (($page - 1) * $page_size) + 1 + $k;
            }
            return $this->success('success', '', $outside_list);
//            $this->assign('outside_list', $outside_list);
        }
        $this->assign('check_option', outside::is_check);

        $title = '';
//        $title = '校外人员入校申请记录';
        $this->assign('pageTitle', $title);
        $this->assign('page_type', 'log');
        $this->assign('go_list', '<div class="apply-list"><a href="view">申请审核</a>');

        $teacherid=0;
        $teacher = Db::name('teacher')->where(['tel'=>$_SESSION['uid'],'nickname'=>$_SESSION['cn']])->find();
        if($teacher){
            $teacherid = $teacher['id'];
        }
        $this->assign('teacherid', $teacherid);
        $sid = Session::get('uid');
        $is_reception = 0;
        $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sid)")->field("name,id")->find();
        if (!empty($reception_info)){
            $is_reception =1;
        }

        $this->assign('is_reception', $is_reception);
        return $this->fetch('view');
    }


    /**
     * 查看详情
     */
    public function info($id = ''){
        $ids = input('id');
        if (!$ids){
            $this->error('该记录不存在');
        }

        $outside_info = $this->model->where('id',$ids)->find();
        $outside_info['card1'] = substr($outside_info['card_id'],0,17);
        $outside_info['card2']= substr($outside_info['card_id'],-1);
        unset($outside_info['card_id']);

        $this->assign('outside_info', $outside_info);

        $title = '';
        $this->assign('pageTitle', $title);
        $this->assign('from', input('from'));
        return $this->fetch();
    }

    /**
     * 审核
     */
    public function ajax($id = ''){
        if ($this->request->isPost()){

            $sid = Session::get('uid');
            if($sid=='200101024'){
                $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sid)")->field("name,id")->column('id');
            }else{
                $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sid)")->field("name,id")->find();
            }
            // 上面是先从校外人员审批人中找，这里是从校友审批人查找
            if (empty($reception_info)){
                $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sf_sid)")->field("id")->find();
            }
            if (!$reception_info){
                $this->error('您无审核权限');
            }

            $params = $this->request->post("row/a");
            //表单验证
            if (!isset($params['id']) || $params['id'] <= 0){
                $this->error('数据异常，审核失败','',$params);
            }
            if (!isset($params['check']) || !in_array($params['check'], [1, 2])){
                $this->error('数据异常，审核失败','',$params);
            }

            if ($params['id']){
                $info = \app\admin\model\Outsideschool::get($params['id']);
                if (!$info){
                    $this->error('数据异常，审核失败','',$params);
                }
                // 车广杰，审核校外人员 。。。于宁老师，张正明老师 可以审核校友入校
                if($sid!='200101024' && $sid!='200201092' && $sid!='199501036'){
                    if ($info['reception_id'] != $reception_info['id']){
                        $this->error('您无审核权限');
                    }
                }
                $update['check_sid'] = session('uid');
                $check_cn = Db::name('teacher')->where(['tel' => session('uid'),'type'=>1])->value('nickname');
                if(!empty(session('cn'))){
                    $cn = session('cn');
                }else{
                    if(!empty($check_cn)){
                        $cn = $check_cn;
                    }else{
                        $cn = '';
                    }
                    if(empty($cn)){
                        $cn = Db::name('outsideschool')->where('check_cn<>""')->where(['check_sid' => session('uid')])->value('check_cn');
                    }
                }
                $update['check_cn'] = $cn;
                $update['is_check'] = $params['check'];
                $update['check_time'] = time();
                $res = Db::name('outsideschool')->where(['id' => $params['id']])->update($update);
                if ($res){
                    $outsideschool_info = Db::name('outsideschool')->where(['id' => $params['id']])->find();
                    if($outsideschool_info['nickname']!='贾小兵'){
                        if(!empty($outsideschool_info['outside_zhxy_json'])){
                            $outside = json_decode($outsideschool_info['outside_zhxy_json'],true);
                            $app_id  = $outside['app_id'];
                            $inst_id = $outside['inst_id'];
                            $task_id = $outside['task_id'];

                            $arr['inst_data'] = [[
                                "inst_id"=>$inst_id,
                                "app_id"=>$app_id,
                                "creator"=>$outsideschool_info['applier_id'],
                                "created"=>date('Y-m-d H:i:s',$outsideschool_info['create_time']),
                                "finished"=>date('Y-m-d H:i:s'),
                                "percent"=>100,
                                "status"=>2,
                                'node_id'=>[$params['id']],
                                "node_name"=>[$cn],
                                "name"=>"校外人员(".$outsideschool_info['nickname'].")进校申请",
                                "form_url_view"=>"https://yqsb.qau.edu.cn/index/outsideschool/view",
                                "form_mobile_url_view"=>"https://yqsb.qau.edu.cn/index/outsideschool/view",
                                "thirdparty_id"=>config('zhxy.outside_thirdparty_id'),
                                "process_pic_url"=>"",
                                "conversion_column"=>['app_id','inst_id','node_id','task_id']
                            ]];
                            $arr['task_data'] = [[
                                "inst_id"=>$inst_id,
                                "app_id"=>$app_id,
                                "task_id"=>$task_id,
                                "node_id"=>$params['id'],
                                "status"=>3,
                                "created"=>date('Y-m-d H:i:s',$outsideschool_info['create_time']),
                                "finished"=>date('Y-m-d H:i:s'),
                                "form_url"=>"https://yqsb.qau.edu.cn/index/outsideschool/view",
                                "form_url_view"=>"https://yqsb.qau.edu.cn/index/outsideschool/view",
                                "form_mobile_url"=>"",
                                "form_mobile_url_view"=>"",
                                "process_pic_url"=>"",
                                "thirdparty_id"=>config('zhxy.outside_thirdparty_id'),
                                "node_name"=>$cn,
                                "number"=>[$update['check_sid']],
                                "conversion_column"=>['app_id','inst_id','node_id','task_id']
                            ]];
                            $url  = config('zhxy.push-task');
                            $data2 =  $this->send_zhxy_msg($url,$arr,'outside');
                            if($outsideschool_info['tel']=='18661473759'){
                                //halt($data2);
                            }
			                if($data2[0] && $data2[1]=='发送成功'){
                                Db::name('outsideschool')->where(['id'=>$params['id']])->update(['is_outside_zhxy'=>1]);
                            }
                        }
                    }

                    $sms_arr = array();
                    $sms_arr['nickname'] = $outsideschool_info['nickname'];
                    $sms_arr['is_check'] = $params['check'];
                    $sms_arr['check_cn'] = $cn;
                    $sms_arr['outsideschool_id'] = $params['id'];
                    if ($params['check'] == 1){
                        if($outsideschool_info['is_schoolfriend']==1){
                            $sm='【青岛农业大学】亲爱的'.$outsideschool_info['nickname'].'校友,您的入校申请已审核,欢迎您回母校! 入校时间:'.$outsideschool_info['admission_starttime'];
                            if(empty($outsideschool_info['zy'])){
                                $sm='【青岛农业大学】亲爱的'.$outsideschool_info['nickname'].'(校友随行人),您的入校申请已审核,欢迎您们回母校!入校时间:'.$outsideschool_info['admission_starttime'];
                            }
                            $send_res = $this->sendtelsms($sm,$outsideschool_info['tel']);
                            $send_sult = json_decode($send_res,true);
                            if(isset($send_sult['success']) && isset($send_sult['id'])){
                                $sms_arr['is_send'] = 1;
                                $sms_arr['send_json'] = $send_res;
                            }else{
                                $sms_arr['is_send'] = 0;
                                $sms_arr['send_json'] = $send_res;
                            }
                            $sms_arr['is_schoolfriend'] = 1;
                            $sms_arr['sm'] = $sm;
                            $sms_arr['tel'] = $outsideschool_info['tel'];
                            $sms_arr['admission_starttime'] = $outsideschool_info['admission_starttime'];
                            $sms_arr['create_time'] = time();
                            Db::name('sendsms')->insert($sms_arr);
                        }
                        $this->success('审核成功', '');
                    } else{
                        if($outsideschool_info['is_schoolfriend']==1 && $params['check']==2 ){
                            $sm='【青岛农业大学】亲爱的'.$outsideschool_info['nickname'].'校友,您的入校申请已驳回。入校信息需完整准确，请认真填写。如有疑问请联系毕业学院!';
                            if(empty($outsideschool_info['zy'])){
                                $sm='【青岛农业大学】亲爱的'.$outsideschool_info['nickname'].'(校友随行人),入校信息需完整准确，请认真填写。如有疑问请联系毕业学院!';
                            }
                            $send_res = $this->sendtelsms($sm,$outsideschool_info['tel']);
                            $send_sult = json_decode($send_res,true);
                            if(isset($send_sult['success']) && isset($send_sult['id'])){
                                $sms_arr['is_send'] = 1;
                                $sms_arr['send_json'] = $send_res;
                            }else{
                                $sms_arr['is_send'] = 0;
                                $sms_arr['send_json'] = $send_res;
                            }
                            $sms_arr['sm'] = $sm;
                            $sms_arr['is_schoolfriend'] = 1;
                            $sms_arr['tel'] = $outsideschool_info['tel'];
                            $sms_arr['admission_starttime'] = $outsideschool_info['admission_starttime'];
                            $sms_arr['create_time'] = time();
                            Db::name('sendsms')->insert($sms_arr);
                        }
                        $this->success('申请已驳回', '');
                    }


                    

                    
                }else{
                    if ($params['check'] == 1){
                        $this->error('审核失败');
                    } else{
                        $this->error('驳回失败');
                    }
                }

            }

        }
    }

    public function sendtelsms($sm = null,$tel = null){
        $sm = urlencode($sm);
        $sm_url = 'http://api.qirui.com:7891/mt?dc=8&un=1267770012&pw=67d0eddeaf4c9ad2dcd0&sm='.$sm.'&da='.$tel.'&tf=3&rf=2&rd=0';
        $data=  file_get_contents($sm_url);
        return $data;
    }

    /**
     * 审核
     */
    public function allpass($ids = null){
        if ($this->request->isPost()){
            $sid = Session::get('uid');
            $is_schoolfriend = 0;
            if($sid=='200101024'){
                $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sid)")->field("name,id")->column('id');
            }else{
                $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sid)")->field("name,id")->find();
                if(empty($reception_info)){
                    $reception_info = ReceptionUnit::whereRaw("find_in_set('{$sid}',sf_sid)")->field("name,id")->find();
                    $is_schoolfriend = 1;
                }
            }
            if (!$reception_info){
                $this->error('您无审核权限');
            }
            if(!empty($ids)){
                $list= \app\admin\model\Outsideschool::where(['id'=>['in',$ids],'is_check'=>0])->select();
            }else{
                $list= \app\admin\model\Outsideschool::where(['reception_id'=>$reception_info['id'],'is_check'=>0,'is_schoolfriend'=>$is_schoolfriend])->select();
            }
            unset($value);
            foreach ($list as $key => $value) {
                $update = [];
                $update['check_sid'] = session('uid');
                $update['check_cn'] = session('cn');
                $update['is_check'] = 1;
                $update['check_time'] = time();
                Db::name('outsideschool')->where(['id' => $value['id']])->update($update);

                $outsideschool_info = Db::name('outsideschool')->where(['id' => $value['id']])->find();
                // 校友发送消息
                if($outsideschool_info['is_schoolfriend']==1){
                    $sms_arr = array();
                    $sms_arr['nickname'] = $outsideschool_info['nickname'];
                    $sms_arr['is_check'] = 1;
                    $sms_arr['check_cn'] = session('cn');
                    $sms_arr['outsideschool_id'] = $value['id'];
                    $sm='【青岛农业大学】亲爱的'.$outsideschool_info['nickname'].'校友,您的入校申请已审核,欢迎您回母校! 入校时间:'.$outsideschool_info['admission_starttime'];
                    if(empty($outsideschool_info['zy'])){
                        $sm='【青岛农业大学】亲爱的'.$outsideschool_info['nickname'].'(校友随行人),您的入校申请已审核,欢迎您们回母校!入校时间:'.$outsideschool_info['admission_starttime'];
                    }
                    $send_res = $this->sendtelsms($sm,$outsideschool_info['tel']);
                    $send_sult = json_decode($send_res,true);
                    if(isset($send_sult['success']) && isset($send_sult['id'])){
                        $sms_arr['is_send'] = 1;
                        $sms_arr['send_json'] = $send_res;
                    }else{
                        $sms_arr['is_send'] = 0;
                        $sms_arr['send_json'] = $send_res;
                    }
                    $sms_arr['is_schoolfriend'] = 1;
                    $sms_arr['sm'] = $sm;
                    $sms_arr['tel'] = $outsideschool_info['tel'];
                    $sms_arr['admission_starttime'] = $outsideschool_info['admission_starttime'];
                    $sms_arr['create_time'] = time();
                    Db::name('sendsms')->insert($sms_arr);
                }
                // 待办任务
                if(!empty($outsideschool_info['outside_zhxy_json'])){
                    $outside = json_decode($outsideschool_info['outside_zhxy_json'],true);
                    $app_id  = $outside['app_id'];
                    $inst_id = $outside['inst_id'];
                    $task_id = $outside['task_id'];

                    $arr['inst_data'] = [[
                        "inst_id"=>$inst_id,
                        "app_id"=>$app_id,
                        "creator"=>$outsideschool_info['applier_id'],
                        "created"=>date('Y-m-d H:i:s',$outsideschool_info['create_time']),
                        "finished"=>date('Y-m-d H:i:s'),
                        "percent"=>100,
                        "status"=>2,
                        'node_id'=>[$value['id']],
                        "node_name"=>[$update['check_cn']],
                        "name"=>"校外人员(".$outsideschool_info['nickname'].")进校申请",
                        "form_url_view"=>"",
                        "form_mobile_url_view"=>"",
                        "thirdparty_id"=>config('zhxy.outside_thirdparty_id'),
                        "process_pic_url"=>"",
                        "conversion_column"=>['app_id','inst_id','node_id','task_id']
                    ]];
                    $arr['task_data'] = [[
                        "inst_id"=>$inst_id,
                        "app_id"=>$app_id,
                        "task_id"=>$task_id,
                        "node_id"=>$value['id'],
                        "status"=>3,
                        "created"=>date('Y-m-d H:i:s',$outsideschool_info['create_time']),
                        "finished"=>date('Y-m-d H:i:s'),
                        "form_url"=>"",
                        "form_url_view"=>"",
                        "form_mobile_url"=>"",
                        "form_mobile_url_view"=>"",
                        "process_pic_url"=>"",
                        "thirdparty_id"=>config('zhxy.outside_thirdparty_id'),
                        "node_name"=>$update['check_cn'],
                        "number"=>[$update['check_sid']],
                        "conversion_column"=>['app_id','inst_id','node_id','task_id']
                    ]];
                    $url  = config('zhxy.push-task');
                    $data2 =  $this->send_zhxy_msg($url,$arr,'outside');

                    if($data2[0] && $data2[1]=='发送成功'){
                        Db::name('outsideschool')->where(['id'=>$value['id']])->update(['is_outside_zhxy'=>1]);
                    }
                }

            }
            $this->success('审核成功', '');
        }
    }


    /*
     * 退出登录
     */
    public function loginout(){
        $_SESSION['uid'] = null;
        $_SESSION['cn'] = null;
        session('uid',null);
        session('cn',null);
        $this->redirect(request()->domain() . '/cas/index.php?logout=1');
        exit;
    }

    /**
     * 黑名单
     * [blacklist description]
     * @param  [type] $nickname [description]
     * @return [type]           [description]
     */
    public function blacklist($nickname){
        $user = [
            ['nickname' => '袁绍东'],
	    ['nickname' => '于绍伟'],
	    ['nickname' => '宋平修'],
        ];
        foreach ($user as $k => $v)
        {
            if($v['nickname']==$nickname)
            {
                return false;
            }
        }
        return true;
    }

    /**
     * 生成appid 事项id
     * [push_apps description]
     * @param  [type] $appid   [description]
     * @param  [type] $appname [description]
     * @return [type]          [description]
     */
    public function push_apps($appid, $appname)
    {
        $url        = config('zhxy')['push-apps'];
        $conversion = true;
        $data       = [
            'conversion' => $conversion,
            'apps'       => [
                [
                    'id'            => $appid,
                    'name'          => $appname,
                    'thirdparty_id' => config('zhxy.outside_thirdparty_id'),
                ]
            ],
        ];
        $re = $this->send_zhxy_msg($url, $data,'outside');
        if (!$re[0]) {
            return 'error';
        }
        return $re;
    }


    /**
     * 
     * [send_zhxy_msg description]
     * @param  [type] $url       [description]
     * @param  [type] $post_data [description]
     * @param  [type] $type      [description]
     * @return [type]            [description]
     */
    private function send_zhxy_msg($url, $post_data,$type = null)
    {
        $token         = (new \app\admin\logic\zhxy\GetAccessToken())->get_token($type);
        if(!$token){
            return 'token is null';
        }
        $domain  = config('zhxy.school_url');
        $urlFull = $domain . $url . '?access_token=' . $token;
        $data = json_post($urlFull, $post_data);
        // halt($data);
        $res = json_decode($data, true);
        if ($res['e'] == 0) {
            return [ true, '发送成功', $res ];
        }
        return [ false, $res['m'], $res ];
    }


    /**
     * 同步数据至importschool
     * [sync_importschool description]
     * @return [type] [description]
     */
    public function sync_importschool($params = []){
        if(!empty($params['applier_id'])){
            $teacher = Db::name('teacher')->where(['tel' => $params['applier_id'],'type'=>1])->find();
            if(!empty($teacher)){
                unset($params['is_uncomfortable']);
                $params['applier_id'] = $teacher['id'];
                $params['update_time'] = $params['create_time'];
                $params['admission_starttime'] = strtotime(date('Y-m-d'),strtotime($params['admission_starttime']));
                $params['admission_endtime'] =strtotime(date('Y-m-d'),strtotime($params['admission_endtime']));
                $params['is_check'] = $params['is_id_check'] =1; 
                Db::name('importschool')->insert($params);
            }
        }
        return ;
    }


    /********************php验证身份证号码是否正确函数*********************/

    public function is_idcard($id)
    {
        $id = strtoupper($id);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = array();
        if(!preg_match($regx, $id))
        {
            return FALSE;
        }
        if(15==strlen($id)) //检查15位
        {
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
          
            @preg_match($regx, $id, $arr_split);
            //检查生日日期是否正确
            $dtm_birth = "19".$arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth))
            {
              return FALSE;
            } else {
              return TRUE;
            }
        }else {     //检查18位
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $id, $arr_split);
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3]. '/' .$arr_split[4];
            if(!strtotime($dtm_birth)) //检查生日日期是否正确
            {
              return FALSE;
            }
            else
            {
              //检验18位身份证的校验码是否正确。
              //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
              $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
              $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
              $sign = 0;
              for ( $i = 0; $i < 17; $i++ )
              {
                // $b = (int) $id{$i};
                $b = (int) $id[$i];
                $w = $arr_int[$i];
                $sign += $b * $w;
              }
              $n = $sign % 11;
              $val_num = $arr_ch[$n];
              if ($val_num != substr($id,17, 1))
              {
                return FALSE;
              } //phpfensi.com
              else
              {
                return TRUE;
              }
            }
        } 
    }

}
